
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

/// <summary>
/// todo: 预览大图
/// author：zwb
/// dateTime： 2021/11/5 14:29
/// filePath： lib/page/show/show_img_page.dart
/// desc: 支持长按图片、缩放 的图片预览
/// <summary>
///
class ShowImgPage extends StatefulWidget {
  final List<String>? imgs;
  late final int? currentIndex;
  final double max; // 最大倍数
  final double min;// 最小倍数
  final bool showTop; // 是否显示顶部
  ShowImgPage({Key? key, this.imgs, this.currentIndex = 0, this.max = 2, this.min = 1, this.showTop:true}) : super(key: key);

  @override
  _ShowImgPageState createState() => _ShowImgPageState();
}

class _ShowImgPageState extends State<ShowImgPage> {
  PageController _pageController = PageController();
  int? currentIndex = 0 ;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed( Duration.zero, (){
      setState(() {
        currentIndex = widget.currentIndex;
        if(widget.imgs!.length >1) _pageController.jumpToPage(widget.currentIndex ?? 0);
      });
    }
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        centerTitle: true,
        leading: IconButton(onPressed: ()=>Navigator.pop(context), icon: Icon(Icons.arrow_back,color: Colors.white,)),
        title: Text(widget.showTop ? "${(currentIndex!+1) > widget.imgs!.length ? 1: (currentIndex!+1) }/${widget.imgs?.length}" : '',style: TextStyle(color: Colors.white),),
      ),
      body: PhotoViewGallery.builder(
        scrollPhysics: const ClampingScrollPhysics(),
        builder: (BuildContext context, int index) {
          return PhotoViewGalleryPageOptions(
            imageProvider: CachedNetworkImageProvider("${widget.imgs?[index]}",),
            initialScale: PhotoViewComputedScale.contained * 1.0,
            minScale: PhotoViewComputedScale.contained * widget.min,
            maxScale: PhotoViewComputedScale.contained * widget.max,
            onTapDown: (a,b,c){
              print("长按");
            },
            onTapUp: (a,b,c){
              print("抬起");
            },
          );
        },
        itemCount: widget.imgs?.length,
        loadingBuilder: (context, event) =>Center(
          child: Container(
            width: 20.0,
            height: 20.0,
            child: CircularProgressIndicator( value: 1,),
            color: Colors.transparent,
          ),
        ),
        backgroundDecoration: BoxDecoration( color: Colors.black,),
        pageController: _pageController,
        onPageChanged: (v) => setState(() => currentIndex = v),
      ),
    ) ;
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _pageController.dispose();
  }
}
